pub(crate)  mod lsip;



use std::sync::{Arc, RwLock};
use std::thread::sleep;
use std::time::Duration;
use lazy_static::lazy_static;
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use tokio::sync::mpsc::{Receiver,Sender};
use crate::lipo_info;

lazy_static!{
    static ref TCP_SENDER: Arc<RwLock<Option<Sender<String>>>> = Arc::new(RwLock::new(None));
}

pub(crate) async fn start_tcp(){
    lipo_info!("构建服务开始".to_string());
    let mut stream = TcpStream::connect("127.0.0.1:5657").await.unwrap();

    let (tx, mut rx) = mpsc::channel::<String>(100);

    TCP_SENDER.write().unwrap().get_or_insert_with(||{
        tx
    });

    let (read, mut writer) = stream.into_split();
    lipo_info!("发送消息".to_string());

    tokio::spawn(async move {
        while let Some(content) = rx.recv().await {
            &writer.write_all(content.as_bytes()).await.unwrap();
        }
    });

    tokio::spawn(async {
        loop {

        }
    });

    send_data("你是啥".to_string());
    let mut buf_reader = BufReader::new(read);
    loop{
        let mut buffer:[u8; 1024] = [0; 1024];
        buf_reader.read(&mut buffer).await.unwrap();
        lipo_info!(format!("内容：{}",String::from_utf8_lossy(&buffer)));
    }

}

pub fn send_data(data:String){
    match TCP_SENDER.read().unwrap().as_ref() {
        Some(tx) => {
            tx.try_send(data).unwrap()
        }
        None => {}
    }
}

pub fn start_test(){
    // let runtime = tokio::runtime::Runtime::new();
    // runtime.unwrap().block_on(async {
    //     start_tcp().await;
    // });
    lsip::test_sip();
}














